<template>
  <div
    id="rank-item"
    @mouseenter="isShow = true"
    @mouseleave="isShow = false"
  >
    <div class="title">
      <img
        :src="'http://localhost:8888' + songsVO.imgUrl"
        alt=""
      />
      <div>
        <p>{{ songsVO.name }}</p>
        <p>{{ songsVO.artist }}</p>
      </div>
    </div>
    <div
      class="icons"
      v-if="isShow"
    >
      <el-icon
        :size="30"
        class="ei"
        @click="insertSong(songsVO.id)"
      >
        <VideoPlay />
      </el-icon>
      <el-icon
        :size="30"
        class="ei"
        @click="jumpToSong()"
      >
        <More />
      </el-icon>
    </div>
  </div>
</template>

<script setup lang="ts">
import type { SongsPageDTO, SongsVO } from '@/types/song'
import { More, VideoPlay } from '@element-plus/icons-vue'
import { ref } from 'vue'
import { getSongAPI, postSongToPlayListAPI } from '@/services/songService.ts'
import type { UnifyResponse } from '@/types/result'
import { useUserStore } from '@/stores/userStore.ts'
import router from '@/utils/router'

const props = defineProps<{
  songsVO: SongsPageDTO
}>()

const isShow = ref(false)

const insertSongsList = async (songData: SongsVO) => {
  const userStore = useUserStore()
  const existingSong = userStore.songsList.find(item => item.songVO.id === songData.id)
  if (existingSong) {
    userStore.songsListPosition = existingSong.order - 1
    userStore.isOpen = true
    return
  }
  if (songData !== null) {
    userStore.songsList.push({
      songVO: songData,
      order: userStore.songsList.length + 1,
    })
    userStore.songsListPosition = userStore.songsList.length - 1
    if (userStore.token === null) {
      return
    }
    const res: UnifyResponse<String> = await postSongToPlayListAPI(songData.id)
    console.log(res.data)
  }
}

const insertSong = async (id: number) => {
  try {
    const res: UnifyResponse<SongsVO> = await getSongAPI(id)
    const song: SongsVO | null = res.data
    song !== null && (await insertSongsList(song))
  } catch (e) {
    console.error(e)
  }
}

const jumpToSong = (): void => {
  router.push({ name: 'Song', params: { id: props.songsVO.id } })
}
</script>

<style scoped>
#rank-item {
  width: 100%;
  background-color: rgba(182, 175, 234, 0.8);
  display: flex;
  justify-content: space-between;
  margin-bottom: 0.3em;
}

img {
  width: 4.2em;
  height: 100%;
}

.title {
  display: flex;
}

p:first-child {
  margin: 0.5em 0 0 0.5em;
  font-weight: bold;
  font-size: 1em;
}

p:last-child {
  margin-left: 0.5em;
  font-size: 0.8em;
}

.icons {
  width: 6em;
  display: flex;
  align-items: center;
  margin-right: 5em;
  justify-content: space-between;
}

.ei {
  cursor: pointer;
}
</style>
